<?php

namespace app\admin\model\base;

use app\BaseModel;

class OfficialAccountMenu extends BaseModel
{
    public $createTime = 'create_time';
    public $updateTime = 'update_time';
    public $autoWriteTimestamp = true;

    /**
     * 获取菜单内容
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getMenu(): array
    {
        $list = self::where('pid', '=', 0)->field(['name', 'type', 'url', 'key', 'id', 'pid', 'content', 'sort', 'media_id', 'path', 'article_id', 'messages_type'])->select()->toArray();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['sub_button'] = self::where('pid', '=', $value['id'])->field(['name', 'type', 'url', 'key', 'id', 'pid', 'content', 'sort', 'media_id', 'path', 'article_id', 'messages_type'])->select()->toArray();
            }
        }
        return $list;
    }

    /**
     * 获取微信公众号创建格式
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getWxMenu(): array
    {
        $list = self::where('pid', '=', 0)
            ->order('sort', 'asc')
            ->field(['name', 'type', 'id', 'url', 'key'])
            ->select()
            ->toArray();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $sub_button = self::where('pid', '=', $value['id'])
                    ->order('sort', 'asc')
                    ->field(['name', 'type', 'url', 'key'])
                    ->select()
                    ->toArray();
                if (!empty($sub_button)) {
                    foreach ($sub_button as $k => $item) {
                        if ($item['type'] == 'view') {
                            unset($sub_button[$k]['key']);
                        }
                        if ($item['type'] == 'click') {
                            unset($sub_button[$k]['url']);
                        }
                    }
                }
                $list[$key]['sub_button'] = $sub_button;
                if (!empty($list[$key]['sub_button'])) {
                    unset($list[$key]['type'], $list[$key]['url'], $list[$key]['key']);
                }
                unset($list[$key]['id']);
            }
        }
        return $list;
    }
}